﻿<%@ WebHandler Language="C#" Class="RbOrderContainerStartHandler" %>

/*Description: 热表订单批次开卡处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20230209
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using System.Collections;
using System.Text;
using System.IO;
using System.IO.Compression;
using BrotliSharpLib;

public class RbOrderContainerStartHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private RbContainerBusiness m_RbContianer = new RbContainerBusiness();
    uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID
    uLMSMfgOrderIBusiness m_Order = uMESBusinessFactory.instance.GetuLMSMfgOrderObject();
    private static object thisLock = new object();

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(ResMessage(false, "数据过期，请重新登录"));
                return;
            }
            switch (action)
            {
                /*-----------------订单批次创建主页面------------------*/
                case "GetMfgOrderList"://获取订单数据
                    GetMfgOrderList(context);
                    break;
                case "GetContainerInfoByMfgOrder"://获取订单数据
                    GetContainerInfoByMfgOrder(context);
                    break;
                case "IsValidOrderContainer"://订单开卡弹窗时验证
                    IsValidOrderContainer(context);
                    break;

                /*-----------------批次创建弹窗方法------------------*/
                case "InitPageData"://初始化无订单创建页面
                    InitPageData(context);
                    break;
                case "GetWorkFlowListDatas":
                    GetWorkFlowListDatas(context);
                    break;
                case "GetStepListDatas":
                    GetStepListDatas(context);
                    break;
                case "GetTeams":
                    GetTeams(context);
                    break;
                case "GetProductFamily":
                    GetProductFamily(context);
                    break;
                case "GetNewContainerNo":
                    GetNewContainerNo(context);
                    break;
                case "GetNewContainerNo2":
                    GetNewContainerNo2(context);
                    break;
                case "CreateRbContainerInfo":
                    lock (thisLock)
                    {
                        CreateRbContainerInfo(context);
                    }
                    break;
                /*-----------------采购订单批次维护方法------------------*/
                case "GetOrderContainerMaintList":
                    GetOrderContainerMaintList(context);
                    break;
                case "SaveRbOrderContainerReceive":
                    SaveRbOrderContainerReceive(context);
                    break;
                /*-----------------扫码采购订单转工维护方法------------------*/
                case "GetScanOrderShipList":
                    GetScanOrderShipList(context);
                    break;
                case "GetParsedScanData":
                    GetParsedScanData(context);
                    break;
                case "SavePurchaseOrderShipData":
                    SavePurchaseOrderShipData(context);
                    break;
                case "IsValidAndCreateMfgOrder":
                    IsValidAndCreateMfgOrder(context);
                    break;
                case "PurchaseOrderShipDataReceive":
                    PurchaseOrderShipDataReceive(context);
                    break;
                case "SaveOrderShipManagePlanDate":
                    SaveOrderShipManagePlanDate(context);
                    break;
                default:
                    context.Response.Write(ResMessage(false, "未找到方法"));
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(ResMessage(false, "系统报错：" + ex.Message));
        }
    }

    /// <summary>
    /// 保存采购订单的计划日期
    /// </summary>
    /// <param name="context"></param>
    private void SaveOrderShipManagePlanDate(HttpContext context)
    {
        DataTable dtShipData = JsonConvert.DeserializeObject<DataTable>(context.Request["shipDatas"].ToString());
        if (dtShipData.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "请选择数据"));
            return;
        }
        DateTime planStartDate;
        if (!DateTime.TryParse(context.Request["planStartDate"].ToString(), out planStartDate))
        {
            context.Response.Write(ResMessage(false, "计划开始日期格式不正确！"));
            return;
        }
        DateTime planEndDate;
        if (!DateTime.TryParse(context.Request["planEndDate"].ToString(), out planEndDate))
        {
            context.Response.Write(ResMessage(false, "计划结束日期格式不正确！"));
            return;
        }
        string updateSql = @"UPDATE rbordershipmanageinfo ri SET ri.planstartdate = to_date('{0}','yyyy-mm-dd hh24:mi:ss'), 
                            ri.planenddate = to_date('{1}','yyyy-mm-dd hh24:mi:ss') WHERE ri.rbordershipmanageinfoid = '{2}' AND ri.status != '3'";
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtShipData.Rows)
        {
            sqlList.Add(string.Format(updateSql, planStartDate, planEndDate, item["rbordershipmanageinfoid"].ToString()));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(ResMessage(true, "更新成功！"));
    }
    /// <summary>
    /// 采购订单数据接收
    /// </summary>
    /// <param name="context"></param>
    private void PurchaseOrderShipDataReceive(HttpContext context)
    {
        DataTable dtShipData = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtShipData.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "请选择数据"));
            return;
        }
        string updateSql = "UPDATE rbordershipmanageinfo ri SET ri.receiveemployeeid = '{0}', ri.receivedate = SYSDATE, ri.status = '1' WHERE ri.rbordershipmanageinfoid = '{1}' AND ri.status = '0'";
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtShipData.Rows)
        {
            sqlList.Add(string.Format(updateSql, m_UserInfo.EmployeeID, item["rbordershipmanageinfoid"].ToString()));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(ResMessage(true, "接收成功！"));
    }

    /// <summary>
    /// 验证件号是否存在并创建订单
    /// </summary>
    /// <param name="context"></param>
    public void IsValidAndCreateMfgOrder(HttpContext context)
    {
        string rbOrderShipManageInfoID = context.Request["rbOrderShipManageInfoID"].ToString();
        string sql = string.Format(@"SELECT ri.mfgordername,ri.materialnum,ri.qty,ri.planstartdate,ri.planenddate,ri.receivedate FROM rbordershipmanageinfo ri WHERE ri.rbordershipmanageinfoid = '{0}' AND ri.status = '1'", rbOrderShipManageInfoID);
        DataTable dtOrderShip = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtOrderShip.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "未找到该数据，请重新查询"));
            return;
        }
        DataRow drShip = dtOrderShip.Rows[0];
        if (string.IsNullOrWhiteSpace(drShip["receivedate"].ToString()))
        {
            context.Response.Write(ResMessage(false, "该计划未接收，请先接收后再开卡！"));
            return;
        }
        if (!string.IsNullOrWhiteSpace(drShip["mfgordername"].ToString()))
        {
            sql = string.Format(@"SELECT p.productid
                        FROM mfgorder m
                        LEFT JOIN PRODUCTBASE PB1  ON PB1.PRODUCTBASEID = m.PRODUCTBASEID
                        LEFT JOIN PRODUCT P  ON P.PRODUCTID = NVL(PB1.REVOFRCDID, m.PRODUCTID)
                        WHERE m.mfgordername = '{0}'
                        AND NOT EXISTS(SELECT 1 FROM container c WHERE c.mfgorderid = m.mfgorderid AND c.status = 1)", drShip["mfgordername"].ToString());
            DataTable dtMfgOrder = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtMfgOrder.Rows.Count == 0)
            {
                context.Response.Write(ResMessage(false, "未找MES订单相关信息"));
                return;
            }
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("Name", drShip["mfgordername"].ToString());
            para.Add("ProductID", dtMfgOrder.Rows[0]["productid"].ToString());
            context.Response.Write(ResMessage(true, "", para));
        }
        else
        {
            sql = string.Format(@"SELECT p.productid,p.productrevision FROM productbase pb
                    LEFT JOIN product p ON p.productid = pb.revofrcdid
                    WHERE pb.productname = '{0}'", drShip["materialnum"].ToString());
            DataTable dtProduct = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtProduct.Rows.Count == 0)
            {
                context.Response.Write(ResMessage(false, string.Format("系统未找到对应的件号：{0}", drShip["materialnum"].ToString())));
                return;
            }
            string mfgOrderName = string.Format("RBCG{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff"));//订单号
            if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM rbordershipmanageinfo ri WHERE ri.mfgordername = '{0}'", mfgOrderName)) != null)
            {
                context.Response.Write(ResMessage(false, "MES订单已存在，请稍后再试"));
                return;
            }
            DatabaseHelper.ExecuteSql(string.Format("UPDATE rbordershipmanageinfo ri SET ri.mfgordername = '{0}' WHERE ri.rbordershipmanageinfoid = '{1}'", mfgOrderName, rbOrderShipManageInfoID));
            /*创建订单*/
            string strInfo = string.Empty;
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("Qty", drShip["qty"].ToString());
            para.Add("PlannedStartDate", Convert.ToDateTime(drShip["planstartdate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss"));
            para.Add("PlannedCompletionDate", Convert.ToDateTime(drShip["planenddate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss"));
            para.Add("UserName", m_UserInfo.APIUserName.ToString());
            para.Add("Password", m_UserInfo.APIPassword.ToString());
            para.Add("ProductName", drShip["materialnum"].ToString());
            para.Add("ProductRevision", dtProduct.Rows[0]["productrevision"].ToString());
            para.Add("Name", mfgOrderName);
            para.Add("FactoryName", m_UserInfo.Factory);
            para.Add("OrderStatus", "打开");
            bool res = m_Order.SaveMonthPlanData(para, ref strInfo);
            if (!res)
            {
                /*订单创建失败，则将对应关系清空*/
                DatabaseHelper.ExecuteSql(string.Format("UPDATE rbordershipmanageinfo ri SET ri.mfgordername = '' WHERE ri.rbordershipmanageinfoid = '{0}'", rbOrderShipManageInfoID));
            }
            //订单创建成功后，将参数返回页面，用于创建批次
            para.Add("ProductID", dtProduct.Rows[0]["productid"].ToString());
            context.Response.Write(ResMessage(res, res ? "添加订单成功" : string.Format("添加订单失败：{0}", strInfo), para));
        }
    }

    /// <summary>
    /// 保存采购订单转工数据
    /// </summary>
    /// <param name="context"></param>
    public void SavePurchaseOrderShipData(HttpContext context)
    {
        DataTable dtShipData = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtShipData.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "请扫码数据"));
            return;
        }
        ArrayList sqlList = new ArrayList();
        StringBuilder sql = new StringBuilder();
        foreach (DataRow item in dtShipData.Rows) //循环保存数据
        {
            sql.Clear();
            sql.AppendLine(@"INSERT INTO rbordershipmanageinfo(rbordershipmanageinfoid,outboundordernum,purchaseordernum,purchaseorderrownum,
                             materialnum,materialname,suppliernum,suppliername,suppliercontainername,specno,specname,unitname,qty,planstartdate,planenddate,createtime,status) VALUES(");
            sql.AppendFormat("'{0}'", Guid.NewGuid().ToString("N"));//主键ID
            sql.AppendFormat(",'{0}'", item["outboundordernum"].ToString());//出库单号
            sql.AppendFormat(",'{0}'", item["purchaseordernum"].ToString());//采购订单号
            sql.AppendFormat(",'{0}'", item["purchaseorderrownum"].ToString());//采购订单行号
            sql.AppendFormat(",'{0}'", item["materialnum"].ToString());//物料号
            sql.AppendFormat(",'{0}'", item["materialname"].ToString());//物料名称
            sql.AppendFormat(",'{0}'", item["suppliernum"].ToString());//供应商编号
            sql.AppendFormat(",'{0}'", item["suppliername"].ToString());//供应商名称
            sql.AppendFormat(",'{0}'", item["suppliercontainername"].ToString());//供应商批次号
            sql.AppendFormat(",'{0}'", item["specno"].ToString());//工序号
            sql.AppendFormat(",'{0}'", item["specname"].ToString());//工序名
            sql.AppendFormat(",'{0}'", item["unitname"].ToString());//单位
            sql.AppendFormat(",'{0}'", item["qty"].ToString());//数量
            sql.AppendFormat(",to_date('{0}','yyyy-mm-dd hh24:mi:ss')", item["planstartdate"].ToString());//计划开始日期
            sql.AppendFormat(",to_date('{0}','yyyy-mm-dd hh24:mi:ss')", item["planenddate"].ToString());//计划结束日期
            sql.AppendFormat(",to_date('{0}','yyyy-mm-dd hh24:mi:ss')", DateTime.Now.ToString());//创建时间
            sql.AppendFormat(",{0})", 0);//默认状态为未接收
            sqlList.Add(sql.ToString());
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(ResMessage(true, "保存成功"));
    }

    /// <summary>
    /// 获取解析后的扫码数据
    /// </summary>
    /// <param name="context"></param>
    public void GetParsedScanData(HttpContext context)
    {
        Dictionary<string, object> resObj = new Dictionary<string, object>();
        try
        {
            string outBoundOrderNum = context.Request["outBoundOrderNum"].ToString();//出库单号（已经扫码的单号，和扫码数据做对比用）
            int currNum = int.Parse(context.Request["currcodenum"].ToString()) + 1;//二维码当前序号（已经扫码的序号，和扫码数据做对比用）
            string scanData = context.Request["scanData"].ToString().Trim();//扫码后的原始数据
            if (string.IsNullOrWhiteSpace(scanData))
            {
                context.Response.Write(ResMessage(false, "请扫描二维码"));
                return;
            }
            string[] scanDatas = scanData.Split('#');//分割原始数据（以#分割）数据结构：LYCD_出库单号_当前二维码序号_总的二维码序号#加密数据
            /*
             * 将scanDatas第一部分进行再分割处理
             */
            string[] headText = scanDatas[0].Split('_');//（前部分又以_分割）数据结构：LYCD_出库单号_当前二维码序号_总的二维码序号
            if (headText.First() != "LYCD")//第一个必须是LYCD开头
            {
                context.Response.Write(ResMessage(false, "转工出库单前缀不是LYCD，请检查扫码数据"));
                return;
            }
            if (!string.IsNullOrWhiteSpace(outBoundOrderNum) && outBoundOrderNum != headText[1])
            {
                context.Response.Write(ResMessage(false, "转工出库单号不一致，请重新扫码"));
                return;
            }
            outBoundOrderNum = headText[1];//第二个数据为出库单号
            if (currNum != int.Parse(headText[2]))//第三个是二维码的序号（如果不是正确序号进行扫码，则提示）
            {
                context.Response.Write(ResMessage(false, "请按照二维码序号进行扫码"));
                return;
            }
            int totalNo = int.Parse(headText[3]);//第三个是二维码的总的序号
            /*
             * 开始解密行数据，并存入datatable
             */
            string decryptionStr = DeEncode(scanDatas[1]);//解密后数据
            //string decryptionStr = @"227447_西安汇腾航空科技有限公司#4500006705,20,019100023001,支架,2201,5,件,0010,工序10,2024-12-03,2024-12-04,[RV]4500006705,30,019100821001,盘形件组件,1245,4,件,0020,工序20,2024-12-03,2024-12-05,[RV]4500006705,580,019155021401,吊耳接头,1234,1,件,0030,工序30,2024-12-03,2024-12-05,[RV]4500008992,1030,10699491,Q/11S 1202-14-12-25,6001,2,件,0040,工序40,2024-12-03,2024-12-05,";
            resObj.Add("decryptionStr", decryptionStr);
            DataTable dtOrder = new DataTable();
            dtOrder.Columns.Add("outboundordernum");//出库单号
            dtOrder.Columns.Add("totalcodenum");//二维码总序号
            dtOrder.Columns.Add("currcodenum");//二维码当前序号
            dtOrder.Columns.Add("suppliernum");//供应商编号
            dtOrder.Columns.Add("suppliername");//供应商名称
            dtOrder.Columns.Add("purchaseordernum");//采购订单号
            dtOrder.Columns.Add("purchaseorderrownum");//采购订单行号
            dtOrder.Columns.Add("materialnum");//物料编号
            dtOrder.Columns.Add("materialname");//物料名称
            dtOrder.Columns.Add("suppliercontainername");//供应商批次号
            dtOrder.Columns.Add("qty");//数量
            dtOrder.Columns.Add("unitname");//单位
            dtOrder.Columns.Add("specno");//工序号
            dtOrder.Columns.Add("specname");//工序名称
            dtOrder.Columns.Add("planstartdate");//计划开始日期
            dtOrder.Columns.Add("planenddate");//计划结束日期
            string[] deDatas = decryptionStr.Split('#');//分割原始数据（以#分割）数据结构：供应商编号_供应商名称#采购订单行数据
            string[] headText1 = deDatas[0].Split('_');//（前部分又以_分割）
            string supplierNum = headText1[0];//第一个数据是供应商编号
            string supplierName = headText1[1];//第二个是供应商名称
            /*获取最终的行数据*/
            string[] orderStrs = deDatas[1].Split(new string[] { "[RV]" }, StringSplitOptions.None);//每一行以[RV]分割
            foreach (string orderStr in orderStrs)
            {
                DataRow drOrder = dtOrder.NewRow();
                drOrder[0] = outBoundOrderNum;
                drOrder[1] = totalNo;
                drOrder[2] = currNum;
                drOrder[3] = supplierNum;
                drOrder[4] = supplierName;
                string[] rowStrs = orderStr.Split(',');//一行数据的每一列以,分割
                for (int i = 0; i < rowStrs.Length; i++)
                {
                    if (i + 5 == dtOrder.Columns.Count)
                    {
                        break;
                    }
                    drOrder[i + 5] = rowStrs[i];//每一列对应起来
                }
                dtOrder.Rows.Add(drOrder);
            }
            resObj.Add("dtOrder", dtOrder);
            context.Response.Write(ResMessage(true, "解析成功", resObj));
        }
        catch (Exception e)
        {
            context.Response.Write(ResMessage(false, string.Format("解析报错：原因：{0}", e.Message), resObj));
        }
    }

    public static string DeEncode(string str)
    {
        var bytes = Convert.FromBase64String(str);
        using (var memoryStream = new MemoryStream(bytes))
        {
            using (var outputStream = new MemoryStream())
            {
                using (var decompressStream = new BrotliStream(memoryStream, CompressionMode.Decompress))
                {
                    decompressStream.CopyTo(outputStream);
                }
                var buffer = outputStream.ToArray();
                return System.Text.Encoding.UTF8.GetString(buffer);
            }
        }
    }

    /// <summary>
    /// 获取扫码后的采购订单转工信息
    /// </summary>
    /// <param name="context"></param>
    public void GetScanOrderShipList(HttpContext context)
    {
        Dictionary<string, string> para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        StringBuilder sql = new StringBuilder();//查询SQL
        sql.AppendFormat(@"SELECT ri.*,c.containername,e.fullname receivename,rc.completedate,ee.fullname completename FROM rbordershipmanageinfo ri 
                            LEFT JOIN containercurrentinfo c ON c.containerid = ri.containerid
                            LEFT JOIN employee e ON e.employeeid = ri.receiveemployeeid
                            LEFT JOIN rbordercontainerreceive rc ON rc.containerid = ri.containerid
                            LEFT JOIN employee ee ON ee.employeeid = rc.completeemployeeid
                            WHERE ri.status = '{0}'", para["status"]);
        //查询采购订单号
        if (!string.IsNullOrWhiteSpace(para["orderName"]))
        {
            sql.AppendFormat(" AND ri.purchaseordernum like '%{0}%'", para["orderName"]);
        }
        //查询件号（对应表数据物料号）
        if (!string.IsNullOrWhiteSpace(para["productName"]))
        {
            sql.AppendFormat(" AND ri.materialnum like '%{0}%'", para["productName"]);
        }
        //供应商名称
        if (!string.IsNullOrWhiteSpace(para["entrustUnit"]))
        {
            sql.AppendFormat(" AND ri.suppliername = {0}", para["entrustUnit"]);
        }
        //供应商批次
        if (!string.IsNullOrWhiteSpace(para["entrustContainer"]))
        {
            sql.AppendFormat(" AND ri.suppliercontainername = {0}", para["entrustContainer"]);
        }

        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(para["pageIndex"]);
        pageDto.PageSize = int.Parse(para["pageSize"]);
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 订单开卡弹窗时验证
    /// </summary>
    /// <param name="context"></param>
    public void IsValidOrderContainer(HttpContext context)
    {
        DataTable dtOrder = GetValidOrderContainerInfo(context.Request["mfgOrderName"].ToString());
        bool res = int.Parse(dtOrder.Rows[0]["qty"].ToString()) > 0 ? true : false;
        context.Response.Write(ResMessage(res, res ? "" : "订单开卡数已满，无法开卡"));
    }

    /// <summary>
    /// 获取订单的批次开卡数和订单信息
    /// </summary>
    /// <param name="mfgOrderName"></param>
    /// <returns></returns>
    private DataTable GetValidOrderContainerInfo(string mfgOrderName)
    {
        string sql = string.Format(@"SELECT (k.orderqty - k.wipqty) qty,k.plannedcompletiondate,k.plannedstartdate FROM (
                    SELECT m.qty orderqty,SUM(NVL(c.originalqty,0)) wipqty,m.plannedcompletiondate,m.plannedstartdate
                    FROM mfgorder m
                    LEFT JOIN container c ON c.mfgorderid = m.mfgorderid AND c.status <> 0 AND c.parentcontainerid IS NULL AND c.qualificationqty = 1
                    WHERE m.mfgordername = '{0}'
                    GROUP BY m.qty,m.plannedcompletiondate,m.plannedstartdate)k", mfgOrderName);
        return DatabaseHelper.Query_ReturnDatTable(sql);
    }

    /// <summary>
    /// 通过订单获取批次信息
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerInfoByMfgOrder(HttpContext context)
    {
        uMESProcessResult result = m_ContainerObj.GetContainerListByMfgOrder(context.Request["mfgOrderId"].ToString());
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 获取订单信息
    /// </summary>
    /// <param name="context"></param>
    public void GetMfgOrderList(HttpContext context)
    {
        Dictionary<string, string> para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        StringBuilder sql = new StringBuilder();//查询SQL
        StringBuilder sqlWhere = new StringBuilder();//查询条件
        //查询订单号
        if (!string.IsNullOrWhiteSpace(para["mfgOrderName"]))
        {
            sqlWhere.AppendFormat(" AND m.mfgordername like '%{0}%'", para["mfgOrderName"]);
        }
        //查询件号
        if (!string.IsNullOrWhiteSpace(para["productName"]))
        {
            sqlWhere.AppendFormat(" AND pb.productname like '%{0}%'", para["productName"]);
        }
        //查询MRP控制者
        if (!string.IsNullOrWhiteSpace(para["mrpControler"]))
        {
            sqlWhere.AppendFormat(" AND ua.attributevalue = {0}", para["mrpControler"]);
        }
        //查询状态
        switch (para["status"])
        {
            case "0": //全部
                sql.AppendFormat(@"SELECT m.mfgorderid,m.mfgordername,p.productid,pb.productname,p.description productdesc,ua.attributevalue mrpcontrol,
                        m.qty orderqty,SUM(NVL(c.originalqty,0)) wipqty,m.plannedstartdate,m.plannedcompletiondate
                        FROM mfgorder m
                        LEFT JOIN Orderstatus ost ON ost.orderstatusid = m.orderstatusid
                        LEFT JOIN PRODUCTBASE PB1  ON PB1.PRODUCTBASEID = m.PRODUCTBASEID
                        LEFT JOIN PRODUCT P  ON P.PRODUCTID = NVL(PB1.REVOFRCDID, m.PRODUCTID)
                        LEFT JOIN PRODUCTBASE PB  ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                        LEFT JOIN USERATTRIBUTE UA ON UA.PARENTID = m.MFGORDERID AND UA.USERATTRIBUTENAME = 'MRP控制者'
                        LEFT JOIN container c ON c.mfgorderid = m.mfgorderid AND c.status <> 0 AND c.parentcontainerid IS NULL AND c.qualificationqty=1
                        WHERE m.factoryid = '{0}' AND m.QTY > 0 AND NVL(ost.orderstatusname,'打开') = '打开'
                        AND NOT EXISTS(SELECT 1 FROM rbordershipmanageinfo ri WHERE ri.mfgordername = m.mfgordername)
                        ", m_UserInfo.FactoryID);
                sql.AppendLine(sqlWhere.ToString());
                sql.AppendLine(" GROUP BY m.mfgorderid,m.mfgordername,p.productid,pb.productname,p.description,ua.attributevalue,m.qty,m.plannedstartdate,m.plannedcompletiondate");
                break;
            case "1": //未开卡
                sql.AppendFormat(@"SELECT m.mfgorderid,m.mfgordername,p.productid,pb.productname,p.description productdesc,ua.attributevalue mrpcontrol,
                        m.qty orderqty,0 wipqty,m.plannedstartdate,m.plannedcompletiondate
                        FROM mfgorder m
                        LEFT JOIN Orderstatus ost ON ost.orderstatusid = m.orderstatusid
                        LEFT JOIN PRODUCTBASE PB1  ON PB1.PRODUCTBASEID = m.PRODUCTBASEID
                        LEFT JOIN PRODUCT P  ON P.PRODUCTID = NVL(PB1.REVOFRCDID, m.PRODUCTID)
                        LEFT JOIN PRODUCTBASE PB  ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                        LEFT JOIN USERATTRIBUTE UA ON UA.PARENTID = m.MFGORDERID AND UA.USERATTRIBUTENAME = 'MRP控制者'
                        WHERE m.factoryid = '{0}' AND m.QTY > 0 AND NVL(ost.orderstatusname,'打开') = '打开' 
                        AND NOT EXISTS (SELECT 1 FROM container c WHERE c.mfgorderid = m.mfgorderid AND c.status <> 0 AND c.parentcontainerid IS NULL AND c.qualificationqty=1)
                        AND NOT EXISTS(SELECT 1 FROM rbordershipmanageinfo ri WHERE ri.mfgordername = m.mfgordername)
                        ", m_UserInfo.FactoryID);
                sql.AppendLine(sqlWhere.ToString());
                break;
            case "2": //已开卡
                sql.AppendFormat(@"SELECT * FROM (SELECT m.mfgorderid,m.mfgordername,p.productid,pb.productname,p.description productdesc,ua.attributevalue mrpcontrol,
                        m.qty orderqty,SUM(NVL(c.originalqty,0)) wipqty,m.plannedstartdate,m.plannedcompletiondate                        
                        FROM mfgorder m
                        LEFT JOIN Orderstatus ost ON ost.orderstatusid = m.orderstatusid
                        LEFT JOIN PRODUCTBASE PB1  ON PB1.PRODUCTBASEID = m.PRODUCTBASEID
                        LEFT JOIN PRODUCT P  ON P.PRODUCTID = NVL(PB1.REVOFRCDID, m.PRODUCTID)
                        LEFT JOIN PRODUCTBASE PB  ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                        LEFT JOIN USERATTRIBUTE UA ON UA.PARENTID = m.MFGORDERID AND UA.USERATTRIBUTENAME = 'MRP控制者'
                        LEFT JOIN container c ON c.mfgorderid = m.mfgorderid AND c.status <> 0 AND c.parentcontainerid IS NULL AND c.qualificationqty=1
                        WHERE m.factoryid = '{0}' AND m.QTY > 0 AND NVL(ost.orderstatusname,'打开') = '打开'
                        AND NOT EXISTS(SELECT 1 FROM rbordershipmanageinfo ri WHERE ri.mfgordername = m.mfgordername)
                        ", m_UserInfo.FactoryID);
                sql.AppendLine(sqlWhere.ToString());
                sql.AppendLine(" GROUP BY m.mfgorderid,m.mfgordername,p.productid,pb.productname,p.description,ua.attributevalue,m.qty,m.plannedstartdate,m.plannedcompletiondate)k WHERE k.wipqty > 0");
                break;
            default:
                sql.Clear();
                break;
        }
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(para["pageIndex"]);
        pageDto.PageSize = int.Parse(para["pageSize"]);
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 获取无订单批次维护数据（批次接收、完工页面）
    /// </summary>
    /// <param name="context"></param>
    public void GetOrderContainerMaintList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("PageNumber", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("OrderName", context.Request["orderName"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("ContainerName", context.Request["containerName"].ToString());
        para.Add("EntrustUnit", context.Request["entrustUnit"].ToString());
        para.Add("EntrustContainer", context.Request["entrustContainer"].ToString());
        uMESProcessResult result = m_RbContianer.GetOrderContainerMaintList(para);
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 保存无订单批次维护数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveRbOrderContainerReceive(HttpContext context)
    {
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());
        if (dtContainer.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "请选择数据"));
            return;
        }
        string msg = "";//返回消息
        bool res = true;//是否成功
        string tranSql = "";//执行sql
        ArrayList sqlList = new ArrayList();
        ReceiveEnum type = (ReceiveEnum)Enum.Parse(typeof(ReceiveEnum), context.Request["type"].ToString());
        switch (type)
        {
            case ReceiveEnum.Receive://接收
                foreach (DataRow item in dtContainer.Rows)
                {
                    tranSql = string.Format("SELECT 1 FROM rbordercontainerreceive r WHERE r.containerid = '{0}'", item["ContainerId"].ToString());
                    if (DatabaseHelper.GetSingle(tranSql) != null)
                    {
                        res = false;
                        msg = string.Format("批次：{0}已接收，请勿重复接收。", item["ContainerName"].ToString());
                        break;
                    }
                    tranSql = string.Format(@"INSERT INTO rbordercontainerreceive(rbordercontainerreceiveid,containerid,receiveemployeeid,receivedate) 
                                        VALUES('{0}','{1}','{2}',SYSDATE)", Guid.NewGuid().ToString(), item["ContainerId"].ToString(), m_UserInfo.EmployeeID);
                    sqlList.Add(tranSql);
                    //如果存在更新采购订单转工记录，更新为接收
                    sqlList.Add(string.Format("UPDATE rbordershipmanageinfo ri SET ri.status = '1' WHERE ri.containerid = '{0}'", item["ContainerId"].ToString()));
                }
                break;
            case ReceiveEnum.Complete://完成
                foreach (DataRow item in dtContainer.Rows)
                {
                    tranSql = string.Format("SELECT 1 FROM rbordercontainerreceive r WHERE r.containerid = '{0}'", item["ContainerId"].ToString());
                    if (DatabaseHelper.GetSingle(tranSql) == null)
                    {
                        res = false;
                        msg = string.Format("批次：{0}未接收，无法完成。", item["ContainerName"].ToString());
                        break;
                    }
                    //批次入库并更新
                    msg = "";
                    res = RbContainerInstoreAndUpdate(item["ContainerId"].ToString(), ref msg);
                    if (!res)
                    {
                        break;
                    }
                    //                    tranSql = string.Format(@"SELECT M.MFGORDERNAME, OT.ORDERTYPENAME, WS.ISLASTSTEP, C.CONTAINERNAME, SB.SPECNAME,S.SPECNO, S.PARENTSPECNO,WR.*
                    //                          FROM (SELECT CSR.CONTAINERID,CSR.WORKFLOWSTEPID, MAX(csr.reportdate) reportdate,
                    //                                       NVL(SUM(CSR.PASSQTY)+sum(nvl(csr.defectqty,0))+sum(nvl(csr.reworkqty,0)), 0) QUALIFIEDQTY,NVL(SUM(CSR.LOSSQTY), 0) SCRAPQTY,CSR.CONTAINERID || CSR.WORKFLOWSTEPID CONTAINERSTEP
                    //                                  FROM CONTAINERSTEPRECORD CSR
                    //                                 WHERE CSR.USECOMPLETED = 1 AND csr.containerid = '{0}' AND csr.containersteprecordid IS NOT NULL
                    //                                 GROUP BY CSR.CONTAINERID, CSR.WORKFLOWSTEPID
                    //                            ) WR
                    //                          LEFT JOIN CONTAINERCURRENTINFO C  ON C.CONTAINERID = WR.CONTAINERID
                    //                          INNER JOIN MFGORDER M  ON M.MFGORDERID = C.MFGORDERID
                    //                          LEFT JOIN ORDERTYPE OT  ON OT.ORDERTYPEID = M.ORDERTYPEID
                    //                          LEFT JOIN WORKFLOWSTEP WS  ON WS.WORKFLOWSTEPID = WR.WORKFLOWSTEPID
                    //                          LEFT JOIN SPEC S ON S.SPECID = WS.SPECID
                    //                          LEFT JOIN SPECBASE SB ON SB.SPECBASEID = S.SPECBASEID
                    //                          LEFT JOIN WRITETOERPRECORD WTE ON WTE.RECORDTYPE = 'workingreport' AND WTE.RECORDID = WR.CONTAINERSTEP AND WTE.ISUSE = 0
                    //                          WHERE NVL(WTE.RECORDID, '0') = '0'", item["ContainerId"].ToString());
                    //                    DataTable dtWorkReport = DatabaseHelper.Query_ReturnDatTable(tranSql);
                    //                    if (dtWorkReport.Rows.Count == 0)
                    //                    {
                    //                        msg = string.Format("批次：{0}没有报工数据或者已推送，无法完成。", item["ContainerName"].ToString());
                    //                        break;
                    //                    }
                    //                    foreach (DataRow drWr in dtWorkReport.Rows)//循环批次的工序报工数据，理论上热表只有一条
                    //                    {
                    //                        sqlList.Add(GetInsertMesWorkingReportSQL(drWr));//插入批次工序报工数据到推送ERP中间表中
                    //                        //插入推送ERP日志记录表
                    //                        sqlList.Add(string.Format(@"INSERT INTO WRITETOERPRECORD
                    //                            (RECORDDATE, RECORDID, RECORDTYPE, RECORDSTATUS，ISSUCCESS) 
                    //                            VALUES (sysdate, '{0}', 'workingreport', '热表报工记录创建成功', 0)", drWr["containerstep"].ToString()));
                    //                    }
                    //更新接收表的完成时间和人
                    sqlList.Add(string.Format("UPDATE rbordercontainerreceive r SET r.completedate = SYSDATE,r.completeemployeeid = '{0}' WHERE r.containerid = '{1}'", m_UserInfo.EmployeeID, item["ContainerId"].ToString()));
                    //更新采购订单转工记录为完工
                    sqlList.Add(string.Format("UPDATE rbordershipmanageinfo ri SET ri.status = '3' WHERE ri.containerid = '{0}'", item["ContainerId"].ToString()));
                }
                break;
            default:
                res = false; msg = "操作类型不明确";
                break;
        }
        if (res)
        {
            res = DatabaseHelper.ExecuteSqlListTran(sqlList);
            msg = res ? "保存成功" : "保存失败";
        }
        context.Response.Write(ResMessage(res, msg));
    }
    /// <summary>
    /// 获取报工数据插入到ERP中间表
    /// </summary>
    /// <param name="drWr"></param>
    /// <returns></returns>
    private string GetInsertMesWorkingReportSQL(DataRow drWr)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"insert into mes_workingreport_table  
                       (mfgordername, containername, specno, sonspecno, reportdate, REPORTQTY, lossqty, lossreason, status,id,CONTAINERSTEP,createdate)
                       values (");
        sql.AppendFormat("'{0}',", drWr["mfgordername"].ToString());//订单号
        sql.AppendFormat("'{0}',", drWr["containername"].ToString());//批次号
        string specname = drWr["specname"].ToString();
        string strSpecNo = drWr["specno"].ToString();
        if (string.IsNullOrWhiteSpace(strSpecNo))
        {
            string[] strArray = specname.Split('-');
            if (strArray.Length >= 3)
            {
                strSpecNo = strArray[strArray.Length - 2];
            }
        }
        sql.AppendFormat("'{0}',", strSpecNo);//工序号
        sql.AppendFormat("'{0}',", "");//子工序号，热表不可能有子工序，为空
        sql.AppendFormat("'{0}',", DateTime.Parse(drWr["reportdate"].ToString()).ToString("YYYY-MM-DD"));//报工日期
        sql.AppendFormat("{0},", drWr["QUALIFIEDQTY"].ToString());//报工数（取自合格数）
        sql.AppendFormat("{0},", drWr["SCRAPQTY"].ToString());//报废数
        sql.AppendLine("'',");//报废原因
        sql.AppendLine("0,");//状态
        sql.AppendFormat("'{0}',", Guid.NewGuid().ToString());//id
        sql.AppendFormat("'{0}',", drWr["containerstep"].ToString());//批次ID+工序ID
        sql.AppendLine("sysdate)");//创建时间
        return sql.ToString();
    }

    /// <summary>
    /// 创建批次
    /// </summary>
    /// <param name="context"></param>
    public void CreateRbContainerInfo(HttpContext context)
    {
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtContainer.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "未需要保存的数据"));
            return;
        }
        DataTable dtProductFamily = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["famliyDatas"].ToString());//机型列表
        if (dtProductFamily.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "未选择机型"));
            return;
        }
        DataRow drContainer = dtContainer.Rows[0];
        if (int.Parse(drContainer["containerQty"].ToString()) <= 0) //填写的批次数量不可小于0
        {
            context.Response.Write(ResMessage(false, "批次数量需大于0"));
            return;
        }
        if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM rbordershipmanageinfo ri WHERE ri.mfgordername = '{0}'", drContainer["orderName"].ToString())) != null && string.IsNullOrWhiteSpace(drContainer["orderShipID"].ToString()))
        {
            context.Response.Write(ResMessage(false, "采购订单未有数据，请刷新后再开卡"));
            return;
        }
        if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM rbordershipmanageinfo ri WHERE ri.rbordershipmanageinfoid = '{0}' AND ri.containerid IS NOT NULL", drContainer["orderShipID"].ToString())) != null)//表示是采购订单转工记录开卡
        {
            context.Response.Write(ResMessage(false, "采购订单已存在批次，不可再次创建"));
            return;
        }
        DataTable dtOrder = GetValidOrderContainerInfo(drContainer["orderName"].ToString());
        int allQty = int.Parse(dtOrder.Rows[0]["qty"].ToString());
        if (allQty <= 0)//如果订单可开卡数小于0，则无法开卡
        {
            context.Response.Write(ResMessage(false, "订单开卡数已满，无法开卡"));
            return;
        }
        if (int.Parse(drContainer["containerQty"].ToString()) > allQty) //如果填写的批次数量大于订单可开卡数据，则不可开卡
        {
            context.Response.Write(ResMessage(false, "批次数量大于订单可开卡数量"));
            return;
        }
        if (drContainer["togetherflag"].ToString().Contains(" "))
        {
            context.Response.Write(ResMessage(false, "大批次存在空格"));
            return;
        }
        if (!drContainer["containerNo"].ToString().Contains(drContainer["togetherflag"].ToString()))
        {
            context.Response.Write(ResMessage(false, "大批次号和批次号未关联"));
            return;
        }
        Tuple<string, string> resT = getContainerNos(drContainer["rbType"].ToString(), drContainer["productPrefix"].ToString());
        if (resT.Item1 != drContainer["togetherflag"].ToString() || resT.Item2 != drContainer["containerNo"].ToString())
        {
            context.Response.Write(ResMessage(false, "大批次号和批次号已更新，请刷新页面"));
            return;
        }
        ContainerStartInfo containerBaseInfo = new ContainerStartInfo();
        containerBaseInfo.ContainerName = drContainer["productPrefix"].ToString() + drContainer["containerNo"].ToString();//批次名（前缀+批次号）
        containerBaseInfo.Qty = drContainer["containerQty"].ToString();//批次数量
        containerBaseInfo.MfgOrder = drContainer["orderName"].ToString();
        containerBaseInfo.MonthPlan = "";//月度计划
        FillContainerDefaultInfo(ref containerBaseInfo, m_UserInfo.FactoryID);
        containerBaseInfo.TogetherFlag = drContainer["productPrefix"].ToString() + drContainer["togetherflag"].ToString();//大批次（前缀+大批次号）
        containerBaseInfo.Factory = m_UserInfo.Factory;
        //containerBaseInfo.CheckTechnique = drContainer["technique"].ToString();
        containerBaseInfo.UOM = drContainer["uOMFieldName"].ToString();
        containerBaseInfo.WorkCenter = drContainer["workCenterName"].ToString();
        containerBaseInfo.Team = drContainer["team"].ToString();
        containerBaseInfo.StartEmployee = m_UserInfo.EmployeeName;

        string product = drContainer["productName"].ToString();
        containerBaseInfo.ProductName = product.Substring(0, product.IndexOf(":"));
        containerBaseInfo.ProductRevision = product.Substring(product.IndexOf(":") + 1);
        containerBaseInfo.ProductuseROR = false;
        //
        string workflowName = drContainer["WorkflowName"].ToString();
        string startWorkflowStep = drContainer["startWorkflowStep"].ToString();
        DataTable dtSubWorkflow = GetSubWorkflowInfo(startWorkflowStep);//查询工序下的通用子工艺，存在，则替换为子工艺
        if (dtSubWorkflow.Rows.Count > 0)
        {
            DataRow drsub = dtSubWorkflow.Rows[0];
            containerBaseInfo.BeginStep = drsub["workflowstepname"].ToString();
            containerBaseInfo.MfgWorkflowName = drsub["workflowname"].ToString();
            containerBaseInfo.MfgWorkflowRevision = drsub["workflowrevision"].ToString();
            containerBaseInfo.MfgWorkflowuseROR = false;
            containerBaseInfo.WorkflowName = drsub["workflowname"].ToString();
            containerBaseInfo.WorkflowRevision = drsub["workflowrevision"].ToString();
            containerBaseInfo.WorkflowuseROR = false;
        }
        else
        {
            containerBaseInfo.BeginStep = drContainer["startWorkflowStepName"].ToString();
            containerBaseInfo.MfgWorkflowName = workflowName.Substring(0, workflowName.IndexOf(":"));
            containerBaseInfo.MfgWorkflowRevision = workflowName.Substring(workflowName.IndexOf(":") + 1, workflowName.LastIndexOf("(") - workflowName.IndexOf(":") - 1);
            containerBaseInfo.MfgWorkflowuseROR = false;
            containerBaseInfo.WorkflowName = containerBaseInfo.MfgWorkflowName;
            containerBaseInfo.WorkflowRevision = containerBaseInfo.MfgWorkflowRevision;
            containerBaseInfo.WorkflowuseROR = false;
        }

        containerBaseInfo.Comment = drContainer["containerComments"].ToString();
        containerBaseInfo.PlannedStartDate = DateTime.Parse(drContainer["startDate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.PlannedCompletionDate = DateTime.Parse(drContainer["completionDate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.ContainerType = "2";
        containerBaseInfo.MilitaryType = drContainer["militaryType"].ToString();
        containerBaseInfo.QualificationQty = "1";//add:Wangjh 20220622
        containerBaseInfo.RbTogetherflag = drContainer["togetherflag"].ToString();
        containerBaseInfo.RbContainerType = drContainer["rbType"].ToString();
        ServerHostInfo serverInfo = new ServerHostInfo();
        serverInfo.UserName = m_UserInfo.APIUserName;
        serverInfo.Password = m_UserInfo.APIPassword;
        containerBaseInfo.ServerHostInfo = serverInfo;
        //填充机型
        string strFamily = string.Empty;
        Dictionary<int, string> listFamily = new Dictionary<int, string>();
        for (int i = 0; i < dtProductFamily.Rows.Count; i++)
        {
            strFamily += " " + dtProductFamily.Rows[i]["ProductFamilyName"].ToString();
            listFamily.Add(i + 1, dtProductFamily.Rows[i]["ProductFamilyName"].ToString());
        }
        containerBaseInfo.MfgBatch = string.Format("型别：{0} |", strFamily.Trim());
        containerBaseInfo.ProductFamilyList = listFamily;
        //扩展属性
        containerBaseInfo.AttributeList = AddContainerAttribute(containerBaseInfo, drContainer, dtSubWorkflow.Rows.Count > 0 ? true : false);
        //开卡
        ResultStatus res = m_ContainerObj.StartContainer(containerBaseInfo);
        if (res.IsError)
        {
            context.Response.Write(ResMessage(false, res.Message.ToString().Replace("Container", "批次：").Replace("already exists", "已存在")));
            return;
        }
        //采购订单ID不为空，则需要关联批次以及自动接收
        if (!string.IsNullOrWhiteSpace(drContainer["orderShipID"].ToString()))
        {
            ArrayList sqlList = new ArrayList();
            string containerId = m_CommonObj.GetTableInfo("container", "containername", containerBaseInfo.ContainerName.ToString()).Rows[0]["containerid"].ToString();
            sqlList.Add(string.Format("UPDATE rbordershipmanageinfo ri SET ri.containerid = '{0}', ri.status = '2' WHERE ri.rbordershipmanageinfoid = '{1}'", containerId, drContainer["orderShipID"].ToString()));
            sqlList.Add(string.Format(@"INSERT INTO rbordercontainerreceive(rbordercontainerreceiveid,containerid,receiveemployeeid,receivedate) 
                                        VALUES('{0}','{1}','{2}',SYSDATE)", Guid.NewGuid().ToString(), containerId, m_UserInfo.EmployeeID));
            DatabaseHelper.ExecuteSqlTran(sqlList);
        }
        m_RbContianer.SendToERPWorkflowInfo(containerBaseInfo.ContainerName.ToString(), m_UserInfo.EmployeeID, ref res.Message);//推送商品工时到ERP
        context.Response.Write(ResMessage(true, "创建成功"));
    }
    /// <summary>
    /// 获取通用子工艺信息
    /// </summary>
    /// <param name="faWorkFlowStepID">父工序ID</param>
    /// <returns></returns>
    private DataTable GetSubWorkflowInfo(string faWorkFlowStepID)
    {
        string sql = string.Format(@"SELECT swb.workflowname,w.workflowrevision,sws.workflowstepname FROM workflowstep ws 
                    LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                    LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                    INNER JOIN workflow w ON w.process_no = s.commonsubworkflow
                    INNER JOIN workflowbase swb on swb.revofrcdid=w.workflowid
                    LEFT JOIN workflowstep sws ON sws.workflowid = w.workflowid
                    WHERE ws.workflowstepid = '{0}'", faWorkFlowStepID);
        return DatabaseHelper.Query_ReturnDatTable(sql);
    }

    /// <summary>
    /// 填充批次默认信息
    /// </summary>
    /// <param name="containerBaseInfo"></param>
    /// <param name="factoryId"></param>
    private void FillContainerDefaultInfo(ref ContainerStartInfo containerBaseInfo, string factoryId)
    {
        DataTable levelAttributes = m_CommonObj.GetFatoryAttributes(factoryId);
        DataRow[] datarows = levelAttributes.Select("USERATTRIBUTENAME='默认所有者'");
        string strOwner = "";
        if (datarows.Length > 0)
        {
            strOwner = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }
        datarows = levelAttributes.Select("USERATTRIBUTENAME='默认层级'");
        string strLevel = "";
        if (datarows.Length > 0)
        {
            strLevel = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }
        string strStart = "";
        if (string.IsNullOrWhiteSpace(containerBaseInfo.MfgOrder.ToString()))
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='无订单开始原因'");
        }
        else
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='订单开始原因'");
        }
        if (datarows.Length > 0)
        {
            strStart = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }

        containerBaseInfo.StartReason = strStart;
        containerBaseInfo.Level = strLevel;
        containerBaseInfo.Owner = strOwner;
        string test = containerBaseInfo.IsSelfMfg.ToString();
        if (containerBaseInfo.IsSelfMfg.ToString() == "True")
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='自投料流程'");
        }
        else
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='领料流程'");
        }
        if (datarows.Length > 0)
        {
            string[] strWorkflows = datarows[0]["ATTRIBUTEVALUE"].ToString().Split('：');
            containerBaseInfo.WorkflowName = strWorkflows.First();
            containerBaseInfo.WorkflowRevision = strWorkflows.Last();
            containerBaseInfo.WorkflowuseROR = false;
        }
    }

    /// <summary>
    /// 添加流水卡扩展属性
    /// </summary>
    /// <param name="containerInfo"></param>
    /// <param name="dr"></param>
    /// <returns></returns>
    private DataTable AddContainerAttribute(ContainerStartInfo containerInfo, DataRow dr, bool isSub)
    {
        DataTable attributeDt = new DataTable();
        attributeDt.Columns.Add("ContainerName");
        attributeDt.Columns.Add("Level");
        attributeDt.Columns.Add("Name");
        attributeDt.Columns.Add("Value");

        DataRow row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "CheckTechnique";
        row["Value"] = containerInfo.CheckTechnique.ToString();
        attributeDt.Rows.Add(row);

        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "BeginStep";
        row["Value"] = containerInfo.BeginStep.ToString();
        attributeDt.Rows.Add(row);

        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "委托单位";
        row["Value"] = dr["EntrustUnit"].ToString();
        attributeDt.Rows.Add(row);

        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "委托批次";
        row["Value"] = dr["EntrustContainer"].ToString();
        attributeDt.Rows.Add(row);
        //如果是通用子工艺开卡，则记录父工艺信息
        if (isSub)
        {
            row = attributeDt.NewRow();
            row["ContainerName"] = containerInfo.ContainerName;
            row["Level"] = containerInfo.Level;
            row["Name"] = "无订单开卡父工艺ID";
            row["Value"] = dr["WorkflowID"].ToString();
            attributeDt.Rows.Add(row);

            row = attributeDt.NewRow();
            row["ContainerName"] = containerInfo.ContainerName;
            row["Level"] = containerInfo.Level;
            row["Name"] = "无订单开卡父工序ID";
            row["Value"] = dr["startWorkflowStep"].ToString();
            attributeDt.Rows.Add(row);
        }
        return attributeDt;
    }

    /// <summary>
    /// 初始化页面数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPageData(HttpContext context)
    {
        DataSet dtset = new DataSet();
        string productID = context.Request["productID"].ToString();
        string orderName = context.Request["orderName"].ToString();
        DataTable dtProduct = m_CommonObj.GetProductInfoByID(productID);
        string productName = dtProduct.Rows[0]["productName"].ToString();
        string productRev = dtProduct.Rows[0]["productrevision"].ToString();
        //获取件号下拉数据
        DataTable subSectionProduct = m_CommonObj.GetSubsectionProductInfo(productName, productID);
        DataTable subSectionProduct_dt = subSectionProduct.DefaultView.ToTable(false, new string[] { "productname", "productid" });
        DataRow subSectionProduct_dr = subSectionProduct_dt.NewRow();
        subSectionProduct_dr["productname"] = productName + ":" + productRev;
        subSectionProduct_dr["productid"] = productID;
        subSectionProduct_dt.Rows.InsertAt(subSectionProduct_dr, 0);//将默认的版本放入第一行
        subSectionProduct_dt.TableName = "subSectionProductDt";
        dtset.Tables.Add(subSectionProduct_dt);

        //获取工艺路线下拉数据
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductName", productName);
        para.Add("ProductID", productID);
        para.Add("ProductRev", productRev);
        para.Add("FactoryID", m_UserInfo.FactoryID);
        DataTable wfdata = m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(para, false, true);
        wfdata.TableName = "sectionWorkFlowDt";
        dtset.Tables.Add(wfdata);
        //获取主制工区下拉数据
        DataTable wcdt = m_CommonObj.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        wcdt.TableName = "sectionWcDt";
        dtset.Tables.Add(wcdt);
        //获取工艺员下拉数据
        DataTable employeedt = m_CommonObj.GetEmplyeeListByRole("工艺员", m_UserInfo.FactoryID);
        if (employeedt.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "分厂没有工艺员"));
            return;
        }
        string strFactoryValue = m_CommonObj.GetFatoryAttributes(m_UserInfo.FactoryID, "工序关联工区班组"); //获取工厂是否工序关联工区班组
        DataRow[] newdr = employeedt.Select();
        DataTable ChildWFTechniquedt = newdr.CopyToDataTable();
        if (strFactoryValue == "是" && !string.IsNullOrWhiteSpace(m_UserInfo.WorkCenterID))
        {
            if (!String.IsNullOrWhiteSpace(m_UserInfo.WorkCenterID))
            {
                DataView dv = employeedt.DefaultView;
                dv.RowFilter = String.Format("WORKCENTERID='{0}'", m_UserInfo.WorkCenterID);
                employeedt = dv.ToTable();
            }
        }
        employeedt.TableName = "sectionEmployDt";
        dtset.Tables.Add(employeedt);
        //获取单位下拉数据
        DataTable dt_UOM = m_CommonObj.GetUom();
        dt_UOM.TableName = "sectionUOMDt";
        dtset.Tables.Add(dt_UOM);
        //获取订单信息
        //ExcuteEntity exuteEntity = new ExcuteEntity("mfgorder", ExcuteEntity.ExcuteTypeEnum.select_);
        //exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("mfgordername", orderName, FieldEntity.FieldTypeEnum.Str) };
        //List<FieldEntity> excuteFieldList = new List<FieldEntity>();
        //excuteFieldList.Add(new FieldEntity("mfgorderid", "", FieldEntity.FieldTypeEnum.Str));
        //excuteFieldList.Add(new FieldEntity("plannedstartdate", "", FieldEntity.FieldTypeEnum.Str));
        //excuteFieldList.Add(new FieldEntity("plannedcompletiondate", "", FieldEntity.FieldTypeEnum.Str));
        //exuteEntity.ExcuteFileds = excuteFieldList;
        //DataTable dtOrder = DatabaseHelper.QueryDataByEntity(exuteEntity);
        DataTable dtOrder = GetValidOrderContainerInfo(orderName);
        dtOrder.TableName = "dtOrder";
        dtset.Tables.Add(dtOrder);
        //获取采购订单转工数据
        string orderShipID = context.Request["orderShipID"].ToString();
        if (!string.IsNullOrWhiteSpace(orderShipID))
        {
            string sql = string.Format(@"SELECT ri.suppliername,ri.suppliercontainername
                                         FROM rbordershipmanageinfo ri WHERE ri.rbordershipmanageinfoid = '{0}'", orderShipID);
            DataTable dtOrderShip = DatabaseHelper.Query_ReturnDatTable(sql);
            dtOrderShip.TableName = "dtOrderShip";
            dtset.Tables.Add(dtOrderShip);
        }
        context.Response.Write(ResMessage(true, "", dtset));
    }

    /// <summary>
    /// 动态获取工艺
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkFlowListDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string productinfo = context.Request.Form["productName"].ToString();
        DataTable wfdata = new DataTable();
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ProductName"] = productinfo.Substring(0, productinfo.IndexOf(":"));
        para["ProductRev"] = productinfo.Substring(productinfo.IndexOf(":") + 1);
        para["FactoryID"] = m_UserInfo.FactoryID;
        wfdata = m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(para, false, true);
        if (wfdata.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "件号没有关联工艺", Result = false }));
            return;
        }
        int index = 0;
        foreach (DataRow item in wfdata.Rows)
        {
            if (!string.IsNullOrWhiteSpace(item["WorkflowID"].ToString()) && !string.IsNullOrWhiteSpace(item["WorkflowName"].ToString()))
            {
                continue;
            }
            else
            {
                index += 1;
            }
            if (index == wfdata.Rows.Count)
            {
                result.Result = false;
                result.Message = "件号关联的工艺信息不完善";
                break;
            }
        }
        if (result.Result)
        {
            result.DBTable = wfdata;
        }
        context.Response.Write(ResMessage(result));

    }

    /// <summary>
    /// 动态获取工序下拉列表
    /// </summary>
    /// <param name="context"></param>
    public void GetStepListDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string workFlowID = context.Request.Form["workFlowID"].ToString();
        DataTable stepTable = m_CommonObj.GetWorkFlowSetpsByWorkflowID(workFlowID);//获取工序列表
        if (stepTable.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "没有工序数据";
        }
        if (result.Result)
        {
            //开始做工序验证
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("WorkflowID", workFlowID);
            para.Add("ChildWorkflow", "1");
            para.Add("GetFactoryValue", "");
            string childerStepIDs = "";//子工艺工序IDs  
            DataTable childwrokflowdt = m_CommonObj.GetWorkFlowSetpsDetailByWorkflowID(para);//获取子工艺
            childwrokflowdt.Columns.Add("CHILDWORKFLOW");
            foreach (DataRow r in childwrokflowdt.Rows)
            {
                if (r["WORKFLOWNAME"].ToString().Contains("空子工艺"))
                {
                    if (childwrokflowdt.Columns.Contains("factoryvalue"))
                    {
                        if (r["factoryvalue"].ToString() == "是")
                        {
                            result.Result = false;
                            result.Message = "子工艺为空子工艺，不允许开卡";
                            break;
                        }
                    }
                }
                childerStepIDs += r["WORKFLOWSTEPID"].ToString() + "，";
                r["CHILDWORKFLOW"] = r["WORKFLOWSTEPNAME"].ToString() + "(" + r["WORKFLOWNAME"].ToString() + ")";
            }
            if (result.Result)
            {
                childerStepIDs = childerStepIDs.Trim('，');
                string strValue_ = m_CommonObj.GetFatoryAttributes(m_UserInfo.FactoryID, "工序关联工区班组"); //获取工厂是否多人派工 燃烧不修改不可以派给其他班组
                if (strValue_ == "是")
                {
                    DataTable dt_ = m_CommonObj.GetWorkFlowStepsWithSpceControlCodeAndCheckStep(workFlowID, m_UserInfo.FactoryID); //获取固定转工固定外委以及检验序工序
                    string NotthisFactoryStepIDs = "";//不用检验的工序，即固定外委或固定转工的工序  
                    foreach (DataRow dr in dt_.Rows)
                    {
                        NotthisFactoryStepIDs += dr["WORKFLOWSTEPID"].ToString() + "，";
                    }
                    NotthisFactoryStepIDs = NotthisFactoryStepIDs.Trim('，');
                    foreach (DataRow item in stepTable.Rows)
                    {
                        if (NotthisFactoryStepIDs.Contains(item["WORKFLOWSTEPID"].ToString()) || childerStepIDs.Contains(item["WORKFLOWSTEPID"].ToString()))
                        {
                            continue;
                        }
                        else
                        {
                            if (!stepTable.Columns.Contains("WORKCENTERID") || string.IsNullOrWhiteSpace(item["WORKCENTERID"].ToString()))
                            {
                                result.Result = false;
                                result.Message = "工序 " + item["WORKFLOWSTEPNAME"].ToString() + " 的工区信息没有维护";
                                break;
                            }
                        }
                    }
                }
            }
            if (result.Result)
            {
                result.DBTable = stepTable;
            }
        }
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 动态获取班组下拉数据
    /// </summary>
    /// <param name="context"></param>
    public void GetTeams(HttpContext context)
    {
        DataTable dt_team = m_CommonObj.GetTeam(context.Request.Form["workcenterID"].ToString());
        context.Response.Write(ResMessage(true, "", dt_team));
    }

    /// <summary>
    /// 动态获取机型列表数据
    /// </summary>
    /// <param name="context"></param>
    public void GetProductFamily(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FamilyType", context.Request.Form["FamilyType"].ToString());
        DataTable pfdt = m_CommonObj.GetProductFamily(para);
        context.Response.Write(ResMessage(true, "", pfdt));
    }

    /// <summary>
    /// 获取最新的批次号
    /// </summary>
    /// <param name="context"></param>
    public void GetNewContainerNo(HttpContext context)
    {
        string productinfo = context.Request.Form["product"].ToString();
        string rbType = context.Request.Form["rbType"].ToString();
        DataTable wfdata = new DataTable();
        Dictionary<string, string> returnData = new Dictionary<string, string>();
        string productName = productinfo.Substring(0, productinfo.IndexOf(":"));
        returnData["RbContainerPrefix"] = productName + "/";//批次前缀
        Tuple<string, string> res = getContainerNos(rbType, returnData["RbContainerPrefix"]);
        returnData["RbTogetherflag"] = res.Item1;//热表大批次
        returnData["RbContainerNo"] = res.Item2;//批次号
        context.Response.Write(ResMessage(true, "", returnData));
    }

    private Tuple<string, string> getContainerNos(string rbType, string prefix)
    {
        int maxIndex = 0;
        string rbTogetherflag = DateTime.Now.ToString("yy") + DateTime.Now.ToString("MM");
        switch (rbType)
        {
            case "1":
                rbTogetherflag += "-R-";
                break;
            case "2":
                rbTogetherflag += "-B-";
                break;
            case "3":
                rbTogetherflag += "-T-";
                break;
            default:
                break;
        }
        maxIndex = m_RbContianer.GetNewestRbTogetherflag(rbTogetherflag);
        rbTogetherflag += (++maxIndex).ToString("D4");
        //查询最大批次号
        maxIndex = m_RbContianer.GetNewestContainerNo(prefix + rbTogetherflag + "-");
        string rbContainerNo = rbTogetherflag + "-" + (++maxIndex).ToString("D2");//批次号
        return new Tuple<string, string>(rbTogetherflag, rbContainerNo);
    }

    /// <summary>
    /// 获取最新的批次号(通过大批次变更)
    /// </summary>
    /// <param name="context"></param>
    public void GetNewContainerNo2(HttpContext context)
    {
        string prefix = context.Request.Form["prefix"].ToString();
        string rbTogetherflag = context.Request.Form["rbTogetherflag"].ToString();
        //查询最大批次号
        int maxIndex = m_RbContianer.GetNewestContainerNo(prefix + rbTogetherflag + "-");
        string containerNO = rbTogetherflag + "-" + (++maxIndex).ToString("D2");//批次号
        context.Response.Write(ResMessage(true, "", containerNO));
    }

    /// <summary>
    /// 热表批次入库并更新批次信息
    /// </summary>
    /// <param name="containerID"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    private bool RbContainerInstoreAndUpdate(string containerID, ref string msg)
    {
        string sql = string.Format(@"SELECT cci.containername,cci.workflowid FROM containercurrentinfo cci WHERE cci.containerid = '{0}' AND cci.isinstore != 1", containerID);
        DataTable dtCon = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtCon.Rows.Count == 0) //批次如果已经入库了，不用进行以下操作
        {
            return true;
        }
        DataRow drCon = dtCon.Rows[0];
        sql = string.Format(@"SELECT NVL(csr.checkqty,0) checkqty,NVL(csr.acceptanceqty,0) passqty,nvl(csr.lossqty,0) lossqty,nvl(csr.acceptanceqty2,0) acceptanceqty2,csr.workflowstepid,
                                    nvl(csr.defectqty,0) defectqty,nvl(csr.reworkqty,0) reworkqty,to_char(csr.createdate,'yyyy-MM-dd hh24:mi:ss') checkdate,csr.checkerid,e.fullname checkempname
                                    FROM containercheckinfo csr 
                                    LEFT JOIN workflowstep ws ON ws.workflowstepid = csr.workflowstepid
                                    LEFT JOIN employee e ON e.employeeid = csr.checkerid
                                    WHERE csr.containerid = '{0}' AND csr.isuse = 0
                                    ORDER BY  ws.sequence DESC", containerID);
        DataTable dtCheck = DatabaseHelper.Query_ReturnDatTable(sql);//获取批次的检验信息
        sql = string.Format(@"SELECT csw.qty,to_char(csw.createdate,'yyyy-MM-dd hh24:mi:ss') reportdate,csw.workerid,csw.workflowstepid
                                FROM containerstepworkreport csw 
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = csw.workflowstepid
                                WHERE csw.containerid = '{0}' AND csw.isuse = 0
                                ORDER BY ws.sequence DESC", containerID);
        DataTable dtReport = DatabaseHelper.Query_ReturnDatTable(sql);//获取批次的报工信息
        if (dtCheck.Rows.Count == 0 || dtReport.Rows.Count == 0)
        {
            msg = string.Format("批次：{0}未完工", drCon["containername"].ToString());
            return false;
        }
        //更新子卡的报工结转表
        sql = string.Format(@"UPDATE containersteprecord csr SET csr.checkdate = to_date('{0}','yyyy-MM-dd hh24:mi:ss'), csr.checkemployeeid = '{1}', csr.checkemployeename = '{2}',csr.usecompleted = 1 WHERE csr.containerid = '{3}' AND csr.workflowstepid = '{4}'",
                            dtCheck.Rows[0]["checkdate"].ToString(), dtCheck.Rows[0]["checkerid"].ToString(), dtCheck.Rows[0]["checkempname"].ToString(), containerID, dtCheck.Rows[0]["workflowstepid"].ToString());
        DatabaseHelper.ExecuteSql(sql);
        /*批次进行入库操作*/
        DataTable dtAttributes = m_CommonObj.GetFatoryAttributes(rbFactoryID);//获取分厂属性
        DataRow[] drsAttr = dtAttributes.Select("USERATTRIBUTENAME='入库流程'");
        string rkWf = string.Empty, rkWfRev = string.Empty, rkStep = string.Empty;//入库工艺，工艺版本，工序
        if (drsAttr.Length > 0)
        {
            string[] strWorkflows = drsAttr[0]["ATTRIBUTEVALUE"].ToString().Split('：');
            rkWf = strWorkflows.First();
            rkWfRev = strWorkflows.Last();
        }
        drsAttr = dtAttributes.Select("USERATTRIBUTENAME='入库工序'");
        if (drsAttr.Length > 0)
        {
            rkStep = drsAttr.First()["ATTRIBUTEVALUE"].ToString();
        }
        ServerHostInfo host = new ServerHostInfo() { UserName = "69400364", Password = "LYCxxzx8000" };
        string strMsg = "";
        if (!m_ContainerObj.ContainerMoveNonStd(host, drCon["containername"].ToString(), rkWf, rkWfRev, rkStep, m_UserInfo.EmployeeName, "", ref strMsg))
        {
            msg = string.Format("批次：{0}移动失败：{1}", drCon["containername"].ToString(), strMsg);
            return false;
        }
        //更新批次入库信息
        DatabaseHelper.ExecuteSql(String.Format("UPDATE containercurrentinfo cci SET cci.bsworkflowid = '{0}',cci.isinstore = 1 WHERE cci.containerid = '{1}'", drCon["workflowid"].ToString(), containerID));
        return true;
    }

    /// <summary>
    /// 返回提示消息
    /// </summary>
    /// <param name="res"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    private string ResMessage(bool res, string msg)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = msg, Result = res };
        return JsonConvert.SerializeObject(result);
    }

    /// <summary>
    /// 返回提示消息(带返回数据)
    /// </summary>
    /// <param name="res"></param>
    /// <param name="msg"></param>
    /// <param name="dt"></param>
    /// <returns></returns>
    private string ResMessage(bool res, string msg, DataTable dt)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = msg, Result = res, DBTable = dt };
        return JsonConvert.SerializeObject(result);
    }

    /// <summary>
    /// 返回提示消息(带返回数据)
    /// </summary>
    /// <param name="res"></param>
    /// <param name="msg"></param>
    /// <param name="ds"></param>
    /// <returns></returns>
    private string ResMessage(bool res, string msg, DataSet ds)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = msg, Result = res, DBDataSet = ds };
        return JsonConvert.SerializeObject(result);
    }

    /// <summary>
    /// 返回提示消息(带返回数据)
    /// </summary>
    /// <param name="res"></param>
    /// <param name="msg"></param>
    /// <param name="dt"></param>
    /// <returns></returns>
    private string ResMessage(bool res, string msg, object obj)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = msg, Result = res, ReturnData = obj };
        return JsonConvert.SerializeObject(result);
    }

    /// <summary>
    /// 返回提示消息(数据对象)
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    private string ResMessage(object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

    /// <summary>
    /// 接收枚举
    /// </summary>
    public enum ReceiveEnum
    {
        Receive = 1,//接收
        Complete = 2
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}